<template>
    <el-dialog
        :visible.sync="dialogVisible"
        title="围栏管理"
        :close-on-press-escape="false"
        :close-on-click-modal="false"
        width="1000px"
    >
        <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
            <el-row>
                <el-col :span="12">
                    <el-form-item label="围栏名称" prop="fenceName">
                        <el-input v-model="formData.fenceName"/>
                    </el-form-item>
                    <el-form-item label="围栏简称" prop="fenceNameShort">
                        <el-input v-model="formData.fenceNameShort"/>
                    </el-form-item>
                    <el-form-item label="附加费" prop="additionalFee">
                        <el-input v-model="formData.additionalFee"/>
                    </el-form-item>
                </el-col>
                <el-col :span="12">

                    <el-form-item label="备注" prop="remark">
                        <el-input v-model="formData.remark"/>
                    </el-form-item>
                    <el-form-item label="排序" prop="sort">
                        <el-input-number v-model="formData.sort" :min="0"/>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-form-item label="绘制地图" prop="points">
                <div style="margin-bottom: 10px; display:flex;">
                    <el-button @click="startDrawPolygon()">{{ drawStatus }}</el-button>
                    <el-button @click="clearPolygon()">清除围栏</el-button>
                    <el-input v-model="formData.lngLat" readonly style=" margin-left:10px;"
                        placeholder="移动地图点击“获取”即可自动获取到中心点经纬度" >
                        <template #append>
                            <el-button slot="reference" @click="getMapCenter()">获取</el-button>
                        </template>
                    </el-input>
                </div>
                <div id="container" style="height:500px;"/>
            </el-form-item>



            <el-form-item>
                <el-popconfirm title="确定保存吗？" @onConfirm="submitForm(this)">
                    <el-button slot="reference" type="primary">保存</el-button>
                </el-popconfirm>
            </el-form-item>
        </el-form>
    </el-dialog>
</template>

<script>
import {CarParkApi} from '@/api/intercity/CarParkApi'
import {CarParkFenceApi} from '@/api/intercity/CarParkFenceApi'
import {Common} from '@/utils/common'
import AMapLoader from '@amap/amap-jsapi-loader'

export default {
    name: 'FenceUpdate',
    components: {},
    data() {
        return {
            formData: {
                id: 0,
                carParkId: '',
                fenceName: '',
                fenceNameShort: '',
                additionalFee:0,
                lng: '',
                lat: '',
                points: '',
                remark: '',
                sort: 0,
                lngLat: ''
            },
            rules: {
                fenceName: [
                    {required: true, message: '请输入围栏名称', trigger: 'blur'},
                    {min: 1, max: 10, message: '长度在 1 到 20 个字符', trigger: 'blur'}
                ],
                fenceNameShort: [
                    {required: true, message: '请输入围栏简称', trigger: 'blur'},
                    {min: 1, max: 10, message: '长度在 1 到 20 个字符', trigger: 'blur'}
                ]
            },
            dialogVisible: false,
            options: [],
            map: null,
            polygonObj: null,
            mouseTool: null,
            polygonEditor: null,
            drawStatus: '开始绘制'
        }
    },
    methods: {
        // 显示组件
        showUpdate(data) {
            let that = this
            this.dialogVisible = true

            this.$nextTick(() => {
                if (data.id > 0) {
                    data.carParkId = data.carParkId.toString()
                    data.lngLat = data.lng + ' , ' + data.lat
                    this.formData = Common.assign(this.formData, data)
                } else {
                    this.formData.carParkId = data.carParkId
                    this.formData.id = 0
                    this.formData.lngLat = ''
                    this.polygonObj = null
                    if (this.$refs['formRef'] !== undefined) {
                        this.$refs['formRef'].resetFields()
                    }
                }

                if(that.map){
                    that.loadMap()
                }else{
                    that.createMap(function(){
                        that.loadMap()
                    })
                }
            })
        },
        createMap(callback){
            let that = this
            window._AMapSecurityConfig = {
                securityJsCode: process.env.VUE_APP_GAODE_SECRET_KEY,
            };
            AMapLoader.load({
                'key': process.env.VUE_APP_GAODE_KEY, // 申请好的Web端开发者Key，首次调用 load 时必填
                'version': '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
                'plugins': ['AMap.MouseTool', 'AMap.PolygonEditor'] // 需要使用的的插件列表，如比例尺'AMap.Scale'等
            }).then((AMap) => {
                const lng = that.formData.lng ? that.formData.lng : 102.709308
                const lat = that.formData.lat ? that.formData.lat : 25.046206
                that.map = new AMap.Map('container', {
                    zoom: 11, // 级别
                    center: [lng, lat] // 中心点坐标
                })
                callback()
            }).catch(e => {
            })
        },
        loadMap() {
            const that = this

            that.map.clearMap()
            that.polygonObj=null
            if(that.polygonEditor){
                that.polygonEditor.close()
                that.polygonEditor = null
            }

            that.mouseTool = new AMap.MouseTool(that.map)

            that.mouseTool.on('draw', function (event) {
                that.drawStatus = '开始绘制'

                // event.obj 为绘制出来的覆盖物对象
                that.endDrawPolygon()
                that.polygonObj = event.obj

                that.polygonEditor = new AMap.PolygonEditor(that.map, that.polygonObj)
                that.polygonEditor.open()
            })

            if (that.formData.points !== '') {
                that.polygonObj = new AMap.Polygon({
                    path: JSON.parse(that.formData.points),
                    strokeColor: '#FF33FF',
                    strokeWeight: 1,
                    strokeOpacity: 0.2,
                    fillOpacity: 0.4,
                    fillColor: '#1791fc',
                    zIndex: 50,
                    bubble: true
                })

                that.map.add([that.polygonObj])

                that.polygonEditor = new AMap.PolygonEditor(that.map, that.polygonObj)
                that.polygonEditor.open()
            }
        },

        // 开始绘制
        startDrawPolygon() {
            if (this.polygonObj == null) {
                this.drawStatus = '绘制中...'
                this.mouseTool.polygon({
                    strokeColor: '#FF33FF',
                    strokeWeight: 2,
                    strokeOpacity: 0.8,
                    fillColor: '#1791fc',
                    fillOpacity: 0.4,
                    // 线样式还支持 'dashed'
                    strokeStyle: 'solid'
                    // strokeStyle是dashed时有效
                    // strokeDasharray: [30,10],
                })
            }
        },

        // 结束绘制
        endDrawPolygon() {
            this.mouseTool.close()
        },

        // 清除绘制
        clearPolygon() {
            this.map.clearMap()
            this.polygonObj = null
            this.formData.points = ''
            this.mouseTool.close()
            this.polygonEditor.close()
        },

        getMapCenter() {
            const centerPoint = this.map.getCenter()

            this.formData.lng = centerPoint.lng
            this.formData.lat = centerPoint.lat
            this.formData.lngLat = centerPoint.lng + ',' + centerPoint.lat
        },

        // 提交表单
        submitForm() {
            const that = this

            let data = Common.deepClone(that.formData);
            data.additionalFee = data.additionalFee*100

            if (that.polygonObj != null) {
                data.points = JSON.stringify(that.polygonObj.getPath())
            }
            that.$refs['formRef'].validate((valid) => {
                if (valid) {
                    if (data.id > 0) {
                        CarParkFenceApi.update(data).then(() => {
                            that.dialogVisible = false
                            that.$emit('refresh')
                        })
                    } else {
                        CarParkFenceApi.insert(data).then(() => {
                            that.dialogVisible = false
                            that.$emit('refresh')
                        })
                    }
                }
            })
        }
    }
}
</script>
